package cn.gson.CRM.controller.product;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.support.spring.annotation.ResponseJSONP;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.gson.CRM.model.dao.permission.MemberDao;
import cn.gson.CRM.model.dao.product.ChaseDetailDao;
import cn.gson.CRM.model.dao.product.ProductDao;
import cn.gson.CRM.model.dao.product.PurchaseDao;
import cn.gson.CRM.model.dao.product.SupplierDao;
import cn.gson.CRM.model.entity.ChaseDetail;
import cn.gson.CRM.model.entity.Member;
import cn.gson.CRM.model.entity.Product;
import cn.gson.CRM.model.entity.Purchase;
import cn.gson.CRM.model.entity.Purchase.State;
import cn.gson.CRM.model.entity.Supplier;
import cn.gson.CRM.model.mapper.PurchaseMapper;
import cn.gson.CRM.model.mapper.SupplierMapper;

/**
 * 供应商与采购单
 * 
 * @author HJK
 *
 */

@Controller
@RequestMapping("purchase")
public class PurchaseController {

	@Autowired
	SupplierDao suppDao;

	@Autowired
	PurchaseMapper purMapper;

	@Autowired
	SupplierMapper suppMapper;

	@Autowired
	PurchaseDao purDao;

	@Autowired
	ProductDao proDao;

	@Autowired
	ChaseDetailDao chaseDao;

	@Autowired
	MemberDao memberDao;

	@RequestMapping
	public String init() {
		return "product/purchase";
	}

	@PostMapping("list")
	@ResponseJSONP
	public Map<String, Object> init(Purchase purchase, @RequestParam(defaultValue = "1") int page,
			@RequestParam(defaultValue = "10") int rows) {
		PageHelper.startPage(page, rows);
		List<Purchase> purs = purMapper.searchPurchase(purchase);
		PageInfo<Purchase> info = new PageInfo<Purchase>(purs);

		Map<String, Object> data = new HashMap<>();
		data.put("rows", purs);
		data.put("total", info.getTotal());
		return data;
	}

	// 修改
	@RequestMapping({ "form", "form/{id}" })
	public String form(@PathVariable(required = false) Long id, Model model) {
		if (id != null) {
			model.addAttribute("pur", purDao.findOne(id));
		}
		Iterable<Member> mbs = memberDao.findAll();

		model.addAttribute("mbs", mbs);
		return "product/purchaseForm";
	}

	@PostMapping("save")
	@ResponseBody
	@Transactional
	public JSONObject savePur(@Valid Purchase pur, Long mbId, BindingResult br) {
		System.out.println(pur);
		JSONObject result = new JSONObject();
		if (br.hasErrors()) {
			System.out.println(br);
			result.put("err", "校验失败！");
		} else {
			if (mbId != null ) {
				if(pur.getTotal()==null){
					pur.setTotal(0.0);
				}
				// 存入供应商和创建人
				pur.setMember(memberDao.findOne(mbId));

				purDao.save(pur);
				result.put("success", true);
			}
		}
		return result;
	}

	@RequestMapping("supp")
	public String supp() {
		return "product/supplier";
	}

	// 修改
	@RequestMapping({ "supp/form", "supp/form/{id}" })
	public String suppForm(@PathVariable(required = false) Long id, Model model) {
		if (id != null) {
			model.addAttribute("r", suppDao.findOne(id));
		}
		return "product/supplierForm";
	}

	@PostMapping("supp/save")
	@ResponseBody
	@Transactional
	public JSONObject save(@Valid Supplier supp, BindingResult br) {
		System.out.println(supp);
		JSONObject result = new JSONObject();
		if (br.hasErrors()) {
			System.out.println(br);
			result.put("err", "校验失败！");
		} else {
			suppDao.save(supp);
			result.put("success", true);
		}
		return result;
	}

	@PostMapping("supp/list")
	@ResponseJSONP
	public Map<String, Object> list(Supplier supplier, @RequestParam(defaultValue = "1") int page,
			@RequestParam(defaultValue = "20") int rows) {
		PageHelper.startPage(page, rows);
		List<Supplier> supps = suppMapper.searchSupplier(supplier);
		PageInfo<Supplier> pageInfo = new PageInfo<Supplier>(supps);

		Map<String, Object> data = new HashMap<>();
		data.put("rows", supps);
		data.put("total", pageInfo.getTotal());
		return data;
	}
	
	@GetMapping("supp/data")
	@ResponseJSONP
	public Iterable<Supplier> datalist(Supplier supplier){
		Iterable<Supplier> supps = suppMapper.searchSupplier(supplier);
		return supps;
	}
	
	@GetMapping("supp/delete/{id}")
	@ResponseBody
	@Transactional
	public String delete(@PathVariable Long id) {
		suppDao.delete(id);
		return "true";
	}

	/**
	 * 显示明细
	 * 
	 * @param id
	 * @param page
	 * @param rows
	 * @return
	 */
	@PostMapping("detail/list/{id}")
	@ResponseJSONP
	public Map<String, Object> detailList(@PathVariable Long id, @RequestParam(defaultValue = "1") int page,
			@RequestParam(defaultValue = "10") int rows) {

		List<ChaseDetail> chases = chaseDao.findById(id);
		
		PageHelper.startPage(page, rows);
		PageInfo<ChaseDetail> info = new PageInfo<ChaseDetail>(chases);

		Map<String, Object> data = new HashMap<>();
		data.put("rows", chases);
		data.put("total", info.getTotal());
		return data;
	}


	/**
	 * 编辑采购明细
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("detail/{id}")
	public String detail(@PathVariable(required = false) Long id, Model model) {
		if (id != null) {
			model.addAttribute("pur", purDao.findOne(id));
		}
		return "product/chaseDetail";
	}

	/**
	 * 查看采购明细
	 */
	@RequestMapping("detail/look/{id}")
	public String detailLook(@PathVariable(required = false) Long id, Model model) {
		if (id != null) {
			model.addAttribute("pur", purDao.findOne(id));
			List<ChaseDetail> chases = chaseDao.findById(id);
			model.addAttribute("rd", chases);
		}
		return "product/chaseDetailForm";
	}

	/**
	 * 采购明细新增和编辑产品
	 * 
	 * @param product
	 * @param model
	 * @return
	 */
	@RequestMapping({"detail/form/{pid}","detail/form/{pid}/{cid}"})
	public String detailForm(@PathVariable(required = true) Long pid,@PathVariable(required = false) Long cid, Model model) {
		model.addAttribute("pur", purDao.findOne(pid));
		if (cid != null) {
			model.addAttribute("pro", chaseDao.findOne(cid));
		}
		Iterable<Supplier> supps = suppDao.findAll();
		model.addAttribute("supps", supps);
		
		return "product/proForm";
	}

	
	/**
	 * 采购已有产品
	 * 
	 * @param product
	 * @param model
	 * @return
	 */
	@RequestMapping("detail/product/{pid}/{proid}")
	public String productForm(@PathVariable(required = true) Long pid,@PathVariable(required = true) Long proid, Model model) {
		model.addAttribute("pur", purDao.findOne(pid));
		if (proid != null) {
			Product p = proDao.findOne(proid);
			if (p != null ) {
				ChaseDetail c = new ChaseDetail();
				c.setName(p.getName());
				c.setCostPrice(p.getCostPrice());
				c.setCount(p.getStock());
				c.setImage(p.getImage());
				c.setSupplier(p.getSupplier());
				model.addAttribute("pro", c);
			}
		}
		Iterable<Supplier> supps = suppDao.findAll();
		model.addAttribute("supps", supps);
		
		return "product/proForm";
	}
	@PostMapping("detail/save")
	@ResponseBody
	@Transactional
	public JSONObject detailSave(@Valid ChaseDetail chaseDetail,Long pid, Long suppId, BindingResult br) {
		JSONObject result = new JSONObject();

		if (br.hasErrors()) {
			System.out.println(br);
			result.put("err", "校验失败！");
		} else {
			Purchase p = purDao.findOne(pid);
			
			chaseDetail.setPurchase(p);
			chaseDetail.setSupplier(suppDao.findOne(suppId));
			//
			chaseDao.save(chaseDetail);
			total(p);
			purDao.save(p);
			
			result.put("success", true);
		}
		return result;
	}
	
	@GetMapping("detail/state/{id}")
	@ResponseBody
	@Transactional
	public String state(@PathVariable Long id){
		List<ChaseDetail> chases = chaseDao.findById(id);
		Purchase p = purDao.findOne(id);
		//没有详情就设为无产品状态
		if(chases.size()>0){
			p.setState(State.NOPAY);
		}else{
			p.setState(State.NODETAIL);
		}
		purDao.save(p);
		return "true";
	}
	
	/**
	 * 删除明细产品
	 * @param id
	 * @return
	 */
	@GetMapping("detail/delete/{id}")
	@ResponseBody
	@Transactional
	public String detailDelete(@PathVariable Long id) {
		Purchase p = chaseDao.findOne(id).getPurchase();
		chaseDao.delete(id);
		
		total(p);
		purDao.save(p);
		return "true";
	}
	public int count(){
		return purDao.findByCount(State.NODETAIL);
	}
	/**
	 * 
	 * 采购单金额
	 * @param pur
	 * @return
	 */
	private Purchase total(Purchase pur) {
		List<ChaseDetail> cds = chaseDao.findById(pur.getId());
		Double count = 0.0 ;
		for (ChaseDetail c : cds) {
			c.setMoney(0.0);
			count += c.getMoney();
		}
		pur.setTotal(count);
		return pur;
	}
}
